<template>
  <div class="thermometryDeviceConfiguration">
    <div class="con">
      <div class="left-tree">
        <div class="search" style="margin-bottom: 10px;">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText2"></el-input>
          </div>
        <el-scrollbar style="height:calc(100% - 55px);width: 100%;">
          <el-tree class="filter-tree" :data="dataList" :expand-on-click-node="true" node-key="id" :props="defaultProps"
            :highlight-current='true' ref="treeleft" @node-click="nodeClick" :filter-node-method="filterNode">
            <template #default="{ node,data }">
              <span class="custom-tree-node">
                <img src="../../../public/static/image/elTree/1.9.png" style="margin-right: 5px;" v-if="data.id" />
                <img src="../../../public/static/image/elTree/variable.png" style="margin-right: 5px;" v-else />
                {{ node.label }}
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="right-table">
        <div class="mytable">
          <div class="search-input-btn" style="width:100%" v-show="isTable">
              <div class="my-search-i">
                <div class="input-small mr-20">
                  <span class="myname">类型：</span>
                  <el-select v-model="typeVal" clearable placeholder="筛选类型" style="width:100px">
                    <el-option v-for="item in typeoptions" :key="item.value" :label="item.typeName" :value="item.type">
                    </el-option>
                  </el-select>
                </div>
                <div class="input-small">
                  <span class="myname">设备型号规格：</span>
                  <el-input v-model="deviceSpecification" clearable placeholder="请输入设备型号规格" style="height:36px"></el-input>
                </div>
                <el-button @click="saveDevce" type="primary" class="search-btn" style="margin-left:12px">绑定</el-button>
              </div>
          </div>
          <div class="myeltable" v-show="!isTable">
            <div class="search-input-btn" style="width:100%">
              <el-scrollbar style="height:100%;width: 100%;">
                <div class="my-search-i">
                  <div class="input-small">
                    <span class="myname">设备型号规格：</span>
                    <el-input v-model="deviceSpecification" clearable placeholder="请输入设备型号规格"></el-input>
                  </div>
                  <el-button @click="saveNextDevce" type="primary" class="search-btn" style="margin-left:12px">绑定</el-button>
                  <el-button @click="del_fn" type="primary"
                    class="last-el-button del-btn-transfer search-btn">移除</el-button>
                </div>
              </el-scrollbar>
            </div>
            <div class="jutitable">
            <el-table id="demo" height="100%" border stripe v-loading="loading" :data="tableData"
              @selection-change="handleSelectionChange" style="width: 100%">
              <el-table-column type="selection" width="44" align="center">
              </el-table-column>
              <el-table-column label="序号" width="60" align="center" type="index"></el-table-column>
              <el-table-column prop="deviceNo" label="编号"> </el-table-column>
              <el-table-column prop="deviceName" label="名称"> </el-table-column>
              <el-table-column prop="deviceSpecification" label="型号规格" align="center"> </el-table-column>
              <el-table-column label="加入时间" align="center">
                <template #default="{row}"><span>{{ date_format(row.createTime)}}</span></template>
              </el-table-column>
            </el-table>
             </div>
          </div>


        </div>
        <div class="decive-tree">
          <div class="search">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          </div>
          <el-scrollbar style="height:calc(100% - 55px);width: 100%;">
            <el-tree :data="rightData" show-checkbox node-key="numNo" :props="devdefaultProps" @check="currentChecked"
              ref="tree" :filter-node-method="filterNode2">
              <template #default="{ node }">
                <div class="custom-tree-node" >
                  <img src="../../../public/static/image/elTree/1.9.png" style="margin-right: 5px;"
                    v-show="node.data.Content.Category=='Organization'" />
                  <img src="../../../public/static/image/elTree/2.1.png" style="margin-right: 5px;"
                    v-show="node.data.Content.Category=='Device'" />
                  <span style="padding-left: 5px;">{{node.data.Content.Name}}</span>
                </div>
               </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { findTreeForUnit, saveConfiguration, findPhotovoltaicDevice, removeDevices,getAllDeviceTypeConfigqiyong} from "../../api/gfSystem";
  import { getReadDeviceTree,getUnitTree } from "../../api/abbNewApi";
  export default {
    components: {
    },
    data() {
      return {
        loading: false,
        dataList: [],
        defaultProps: {
          children: 'children',
          label: 'unitName',
        },
        rightData: [],
        devdefaultProps: {
          children: 'ChildDatas',
          label: 'Content.Name'
        },
        filterText: '',
        filterText2:"",
        checkedNodes: [],
        typeVal: "",
        typeoptions2: [
          {
            'label': '逆变器',
            'value': 'INVERTER',
          },
          {
            'label': '汇流箱',
            'value': 'COMBINER_BOX',
          },
          {
            'label': '并网柜',
            'value': 'COMBINED_CABINET',
          },
          {
            'label': '箱变',
            'value': 'BOX_TYPE',
          },
          {
            'label': '气象站',
            'value': 'METEOROLOGICAL_STATION',
          },
          {
            'label': '充电桩',
            'value': 'CHARGING_PILE',
          },
          {
            'label': '空调',
            'value': 'AIR_CONDITIONER',
          },
          {
            'label': '照明',
            'value': 'LIGHTING',
          },
          {
            'label': '储能',
            'value': 'ENERGY_STORAGE',
          },
          {
            'label': '路灯',
            'value': 'STREET_LAMP',
          }
        ],
        typeoptions:[],
        // typeoptions: [
        //   {
        //     'label': 'PCS',
        //     'value': 'PCS',
        //   },
        //   {
        //     'label': 'BMS',
        //     'value': 'BMS',
        //   },
        //   {
        //     'label': '电表',
        //     'value': 'AMMETER',
        //   },
        //   {
        //     'label': '除湿机',
        //     'value': 'DEHUMIDIFIERS',
        //   },
        //   {
        //     'label': '消防',
        //     'value': 'FIREFIGHTING',
        //   },
        //   {
        //     'label': '液冷',
        //     'value': 'LIQUID_COOLING',
        //   },
        //   {
        //     'label': '网络继电器',
        //     'value': 'NETWORK_RELAYS',
        //   },
        // ],
        mynowRow: "",
        deviceSpecification: "",
        isTable: true,
        tableData: [],
        multipleSelection: [],
        unitId:""
      };
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      filterText2(val) {
        this.$refs.treeleft.filter(val);
      },

    },
    computed: {
      
    },

    mounted() {
      getUnitTree().then(res => {
        if(res.success){
          this.unitId = res.data.id 
          this.getfindTreeForUnit()
        }
          
      })
      this.getDeviceTypes()
      
      var num = 0
      //设备列表
      getReadDeviceTree().then(res => {
        var recursiveFunction = function () {
          const getStr = function (list) {
            list.forEach(function (row) {
              if (row.ChildDatas.length != 0) {
                row.numNo = num++
                getStr(row.ChildDatas)
              } else {
                row.numNo = num++
                row['disabled'] = false
              }
            })
          }
          getStr(res.data)
        }
        recursiveFunction()
        this.rightData = res.data
      })
    },

    methods: {
       // 转换时间戳
      date_format(value) { //value就是插值的数据
        if(!value) {
          return ""
        }
        var arr=['SByte','Int16','Int32','Byte','UInt16','Uint32','Single','Boolean','String','Byte[]','Double','Decimal','Int64','UInt64','SByte']

        return arr[value]
      },
      //获取设备类型
      getDeviceTypes(){
         getAllDeviceTypeConfigqiyong().then(res => {
             if(res.code == 200){
                this.typeoptions = res.data
             }           
         })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.unitName.indexOf(value) !== -1;
      },
      filterNode2(value, data) {
        if (!value) return true;
        return data.Content.Name.indexOf(value) !== -1;
      },
      //表格选中
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //移除表格选中
      del_fn() {
        this.$confirm(`是否移除选中的设备`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var decStr = ""
          this.multipleSelection.forEach(item => {
            decStr += ',' + item.id
          })
          removeDevices({ "ids": decStr.slice(1) }).then(res => {
            // console.log("移除选中");
            if (res.code == 200) {
              this.getfindPhotovoltaicDevice()
              this.$message({ showClose: true, message: '移除成功', type: 'success' });
            } else {
              res.message ? this.$message.error(res.message) : this.$message.error('移除失败');

            }
          })
        }).catch(() => {
          // ...
        });
      },
      //批量删除

      //获取单位下光伏设备类型树
      getfindTreeForUnit() {
        // console.log("this.unitId",this.unitId);
        var d = {
          'unitId': this.unitId.id
        }

        var newArr = []
        findTreeForUnit(d).then(res => {

          if (res.code == 200) {

            var recursiveFunction = function () {
              const getStr = function (list) {
                list.forEach(function (row) {
                  if (row.children && row.children.length != 0) {
                    newArr = []
                    row.deviceTypes.forEach(item => item.myId = row.id)
                    newArr = row.children.concat(row.deviceTypes)
                    row.children = newArr
                    getStr(row.children)
                  } else {
                    newArr = []
                    if (row.deviceTypes) {
                      row.deviceTypes.forEach(item => item.myId = row.id)
                      newArr = row.children.concat(row.deviceTypes)
                    }
                    row.children = newArr
                  }
                })
              }
              getStr(res.data)
            }
            recursiveFunction()
            res.data = JSON.parse(JSON.stringify(res.data).replace(/desc/g, "unitName"))
            this.dataList = res.data
          }

        })


      },
      //左边树形结构点击
      nodeClick(row) {

        this.deviceSpecification = ""
        this.mynowRow = row
        if (row.myId) {
          this.isTable = false
          this.getfindPhotovoltaicDevice()
        } else {
          this.isTable = true

        }
      },
      //右边设备树形结构
      currentChecked(nodeObj, SelectedObj) {
        this.checkedNodes = SelectedObj.checkedNodes
        this.checkedNodes = this.checkedNodes.filter(item => item.Content.Category == 'Device')
      },
      //给单位绑定设备
      saveDevce() {
        var d = []
        if (this.deviceSpecification == '') {
          this.$message({ showClose: true, message: '请先填写设备型号规格！', type: 'warning' });
          return
        }
        if (this.checkedNodes == []) {
          this.$message({ showClose: true, message: '请选择设备再进行绑定！', type: 'warning' });
          return
        }
        this.checkedNodes.forEach(item => {
          d.push({
            'deviceName': item.Content.Name,
            'deviceNo': item.Content.Id,
            'deviceType': this.typeVal,
            'unitId': this.mynowRow.id,
            'deviceSpecification': this.deviceSpecification
          })
        })
        saveConfiguration(d).then(res => {
          if (res.code == 200) {
            this.getfindTreeForUnit()
            this.$refs.tree.setCheckedKeys([]);
            this.deviceSpecification = ""
            this.$message({ showClose: true, message: '绑定成功', type: 'success' });
          } else {
            res.message ? this.$message.error(res.message) : this.$message.error('绑定失败');

          }
        })
      },
      //直接给下一级绑定设备
      saveNextDevce() {
        var d = []
        if (this.deviceSpecification == '') {
          this.$message({ showClose: true, message: '请先填写设备型号规格！', type: 'warning' });
          return
        }
        if (this.checkedNodes == []) {
          this.$message({ showClose: true, message: '请选择设备再进行绑定！', type: 'warning' });
          return
        }

        var filterArr = this.typeoptions.filter(item => item.typeName == this.mynowRow.unitName)
        this.checkedNodes.forEach(item => {
          d.push({
            'deviceName': item.Content.Name,
            'deviceNo': item.Content.Id,
            'deviceType': filterArr[0].type,
            'unitId': this.mynowRow.myId,
            'deviceSpecification': this.deviceSpecification
          })
        })
        saveConfiguration(d).then(res => {
          if (res.code == 200) {
            this.getfindPhotovoltaicDevice()
            this.$refs.tree.setCheckedKeys([]);
            this.deviceSpecification = ""
            this.$message({ showClose: true, message: '绑定成功', type: 'success' });
          } else {
            res.message ? this.$message.error(res.message) : this.$message.error('绑定失败');

          }
        })
      },
      //根据单位id和类型编码获取设备列表
      getfindPhotovoltaicDevice() {
        this.loading = true
        var d = {
          'code': this.mynowRow.code,
          'unitId': this.mynowRow.myId
        }
        findPhotovoltaicDevice(d).then(res => {
          // console.log("获取表格", res);
          this.loading = false
          if (res.code == 200) {
            this.tableData = res.data
          }
        })
      }
    },
    
  };
</script>

<style lang="scss" scoped>
  .thermometryDeviceConfiguration {
    .con {
      width: 100%;
      height: 100%;
      display: flex;

      .left-tree {
        width: 300px;
        height: 100%;
        background-color: #fff;
        padding: 12px 20px;
        box-sizing: border-box;
        margin-right: 8px;
      }

      .right-table {
        width: calc(100% - 308px);
        height: 100%;
        background-color: #fff;
        box-sizing: border-box;
        display: flex;

        .mytable {
          width: calc(100% - 300px);
          height: 100%;
          padding: 12px 20px;
          box-sizing: border-box;

          .input-small .myname {
            white-space: nowrap;
          }
          .myeltable {
             width: 100%;
             height: 100%;
             .jutitable {
               width: 100%;
               height: calc(100% - 60px);
             }
          }

        }

        .decive-tree {
          width: 300px;
          height: 100%;
          padding: 12px 20px;
          box-sizing: border-box;
          border-left: 1px solid #cccccc;

          .search {
            margin-bottom: 10px;
          }

        }
      }
    }
  }
</style>